﻿using Autofac.Integration.Mvc;
using CNKI.TPI.Web.Search.Model;
using KNet.Data.Entity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CNKI.TPI.Web.Base
{
    public class ColumnAliasHelper
    {
        private static Hashtable columnInfo = new Hashtable();
        private static IDataContext context = AutofacDependencyResolver.Current.GetService<IDataContext>();
        /// <summary>
        /// 获得实际字段名的别名----LZG添加
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="FieldName"></param>
        /// <returns></returns>
        public static string GetAliasColumn(string dbCode, string FieldName)
        {
            string result = "";
            try
            {
                Expression<Func<SYS_CMS_DATABASE_FIELD, bool>> query = c => (c.DatabaseCode == dbCode) && (c.Field == FieldName);
                IList<SYS_CMS_DATABASE_FIELD> fieldInfo = context.Get<SYS_CMS_DATABASE_FIELD>(query);
                if (fieldInfo != null && fieldInfo.Count > 0)
                {
                    result = fieldInfo[0].Alias;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 获得别名的实际字段名
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="alias"></param>
        /// <returns></returns>
        public static string GetColumn(string dbCode, string alias)
        {
            string result = "";
            try
            {
                string key = dbCode + "#" + alias;
                string cacheAlias = null;
                if (!string.IsNullOrEmpty(alias))
                {
                    cacheAlias = GetAliasInCache(key);
                    if (string.IsNullOrEmpty(cacheAlias))//存在
                    {
                        result = GetFromDb(dbCode, alias, key);
                    }
                    else
                    {
                        result = cacheAlias;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        private static string GetAliasInCache(string key)
        {
            string result = "";
            string str = "";
            lock (columnInfo)
            {
                if (columnInfo.ContainsKey(key))//存在
                {
                    str = (string)columnInfo[key];
                    string[] arraystr = str.Split('#');
                    string minus = ConfigHelper.GetAppSettingsValue("TimeSpanTable");//获取配置文件设置的时间间隔
                    if (minus != "")
                    {
                        TimeSpan ts = DateTime.Now - DateTime.Parse(arraystr[1]);//与当前时间比较
                        if (ts.TotalMinutes <= double.Parse(minus))//未超过时间间隔
                        {
                            result = arraystr[0];
                        }
                    }
                    else//如果没有设置时间间隔则直接获取
                    {
                        result = arraystr[0];
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 从数据库获取对应的别名
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="alias"></param>
        /// <returns></returns>
        private static string GetFromDb(string dbCode, string alias, string key)
        {
            string result = "";
            result = GetFieldInfo(dbCode, alias);
            if (string.IsNullOrEmpty(result))
            {
                result = alias;
            }
            lock (columnInfo)
            {
                if (columnInfo.ContainsKey(key))
                {
                    columnInfo.Remove(key);//如果存在已有的赋值，则先移除
                }
                columnInfo.Add(key, result + "#" + DateTime.Now);
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbCode"></param>
        /// <param name="alias"></param>
        /// <returns></returns>
        private static string GetFieldInfo(string dbCode, string alias)
        {
            string result = "";
            try
            {
                //Expression<Func<SYS_CMS_DATABASE_FIELD, bool>> query = c => (c.DatabaseCode == dbCode) && (c.Alias == alias);
                ExpressionCombine<SYS_CMS_DATABASE_FIELD> exp = new ExpressionCombine<SYS_CMS_DATABASE_FIELD>();
                exp.And("DatabaseCode", OperatorType.Equal, dbCode);
                exp.And("Alias", OperatorType.Equal, alias);
                IList<SYS_CMS_DATABASE_FIELD> fieldInfo = context.Get<SYS_CMS_DATABASE_FIELD>(exp.Compile());
                if (fieldInfo != null && fieldInfo.Count > 0)
                {
                    result = fieldInfo[0].Field;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static string GetContent(DataTable dt, string dbCode, int rowIndex, string column)
        {
            string result = "";
            try
            {
                column = GetColumn(dbCode, column);
                result = GetContent(dt, rowIndex, column);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
        /// <summary>
        /// 获取不标红的数据
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <param name="isred"></param>
        /// <returns></returns>
        public static string GetContent(DataTable dt, string dbCode, int rowIndex, string column, int isred)
        {
            string result = "";
            try
            {
                column = GetColumn(dbCode, column);
                result = GetContent(dt, rowIndex, column);
                if (isred == 0)
                {
                    result = result.Replace("<span style=\"color:red;margin: 0px\">", "");
                    result = result.Replace("</span>", "");
                }

            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static string GetContent(DataTable dt, int rowIndex, string column)
        {
            string result = "";
            try
            {
                if (!string.IsNullOrEmpty(column))
                {
                    if (dt.Rows.Count > rowIndex && dt.Columns.Contains(column))
                    {
                        if (typeof(DateTime) == dt.Rows[rowIndex][column].GetType())
                        {
                            result = ((DateTime)dt.Rows[rowIndex][column]).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            result = dt.Rows[rowIndex][column].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static string GetContent(DataTable dt, int rowIndex, int columnIndex)
        {
            string result = "";
            try
            {
                if (dt.Rows.Count > rowIndex && dt.Columns.Count > columnIndex)
                {
                    if (typeof(DateTime) == dt.Rows[rowIndex][columnIndex].GetType())
                    {
                        result = ((DateTime)dt.Rows[rowIndex][columnIndex]).ToString("yyyy-MM-dd");
                    }
                    else
                    {
                        result = dt.Rows[rowIndex][columnIndex].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static string GetContent(DataRow dr, string dbCode, string column)
        {
            string result = "";
            try
            {
                column = GetColumn(dbCode, column);
                result = GetContent(dr, column);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dbCode"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public static string GetContent(DataRow dr, string column)
        {
            string result = "";
            try
            {
                if (!string.IsNullOrEmpty(column))
                {
                    if (dr.Table.Columns.Contains(column))
                    {
                        if (typeof(DateTime) == dr[column].GetType())
                        {
                            result = ((DateTime)dr[column]).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            result = dr[column].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 截取固定长度的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string SubContent(string item, int len)
        {
            if (!String.IsNullOrEmpty(item) && len > 0)
            {
                if (item.Contains("<span style=\"color:red;margin: 0px\">") && item.Contains("</span>"))
                {
                    string newitem = "";
                    item = StringHelper.UnDealInfo(item);
                    item = item.Replace("<span style=\"color:red;margin: 0px\">", "#");//替换便于计算
                    item = item.Replace("</span>", "$");
                    

                    int n = 0;
                    int num1 = 0;
                    int num2 = 0;//统计截取后# $出现次数
                    foreach (char str in item)
                    {
                        newitem = newitem + str;
                        switch (str)
                        {
                            case '#': num1++; break;
                            case '$': num2++; break;
                            default: n++; break;
                        }
                        if (n == len)
                        {
                            break;
                        }
                    }

                    if ((num2 != 0 && num1 % num2 != 0) || (num2 == 0 && num1 > 0)) //标记不配对
                    {
                        newitem = newitem + "$";
                    }
                    item = StringHelper.DealInfo(item);
                    newitem = newitem.Replace("#", "<span style=\"color:red;margin: 0px\">");//替换
                    newitem = newitem.Replace("$", "</span>");
                    
                    if (n == len)
                    {
                        newitem = newitem + "...";
                    }
                    item = newitem;
                }
                else
                {
                    item = StringHelper.UnDealInfo(item);
                    if (len < item.Length)
                    {
                        item = item.Substring(0, len) + "...";
                    }
                    item = StringHelper.DealInfo(item);
                }
            }
            return item;
        }
        /// <summary>
        /// 替换转义字符，输出时不被转义
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string ChangeStr(string item)
        {
            if (!String.IsNullOrEmpty(item) && ConfigHelper.IsHtmlEscape())
            {
                item = item.Replace("&", "&amp;");
                item = item.Replace("<", "&lt");
                item = item.Replace(">", "&gt");
            }
            return item;
        }

        public static string UnChangeStr(string item)
        {
            if (!String.IsNullOrEmpty(item) && ConfigHelper.IsHtmlEscape())
            {
                item = item.Replace("&amp;", "&");
                item = item.Replace("&lt", "<");
                item = item.Replace("&gt", ">");
            }
            return item;
        }


        /// <summary>
        /// 获取分页格式
        /// </summary>
        /// <param name="currentIndex">当前页</param>
        /// <param name="total">总页数</param>
        /// <param name="disPgae">默认显示页数，当页数大于该数值时，按规定格式显示</param> 
        /// <returns></returns>
        public List<String> GetPageList(int currentIndex, int total, int disPage)
        {
            List<String> pageList = new List<string>();
            if (disPage > total)
            {
                for (int i = 1; i <= total; i++)
                {
                    pageList.Add(i.ToString());
                }
                return pageList;
            }

            for (int i = 1; i <= disPage; i++)
            {
                if (i < 3)
                {
                    pageList.Add(i.ToString());
                }
                else if (i == 3)
                {
                    if (currentIndex > 5)
                    {
                        pageList.Add("0");
                    }
                    else
                    {
                        pageList.Add(i.ToString());
                    }
                }
                else if (i < (disPage - 1))
                {
                    if (currentIndex >= 5)
                    {
                        if ((currentIndex + (i - 4)) >= total)
                        {
                            continue;
                        }
                        pageList.Add((currentIndex + (i - 5)).ToString());
                    }
                    else
                    {
                        pageList.Add(i.ToString());
                    }
                }
                else if (i == (disPage - 1))
                {
                    if (total - currentIndex > 2)
                    {
                        pageList.Add("0");
                    }
                    else
                    {
                        pageList.Add((total - 1).ToString());
                    }
                }
                else
                {
                    pageList.Add(total.ToString());
                }
            }

            return pageList;
        }

        /// <summary>
        /// 去除标红显示
        /// </summary>
        /// <param name="dbCode"></param>
        /// <returns></returns>
        public static string GetContentNoRed(string dbCode)
        {
            try
            {
                dbCode = dbCode.Replace("<span style=\"color:red;margin: 0px\">", "");
                dbCode = dbCode.Replace("</span>", "");
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return dbCode;
        }
        /// <summary>
        /// 去除标红显示
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DataTable GetContentNoRed(DataTable dt)
        {
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn fc in dt.Columns)
                {
                    dr[fc.ColumnName] = dr[fc.ColumnName].ToString().Replace("<span style=\"color:red;margin: 0px\">", "").Replace("</span>", "");
                }
            }
            return dt;
        }

    }
}
